<?php
/**
 * Created by PhpStorm.
 * User: Sixstar-Peter
 * Date: 2019/4/12
 * Time: 22:33
 */

$workerNum = 2;
$pool = new Swoole\Process\Pool($workerNum);

$pool->on("WorkerStart", function ($pool, $workerId) {
    echo "Worker#{$workerId} is started\n";
    $running = true;
    pcntl_signal(SIGTERM, function () use (&$running) {
        $running = false;
    });
    ini_set('default_socket_timeout', -1); //设置永不超时
    $retryLimit = 3; //重试三次
    $reties = 0; //尝试次数
    RETRY:{
        try {
            $redis = new Redis();
            $redis->pconnect('127.0.0.1', 6379);
            $key = "key1";
            while ($running) {
                $msg = $redis->brpop($key, 10); //任务取出来
                pcntl_signal_dispatch(); //信号触发,打断
                if ($msg == null) continue;
                var_dump($msg);
            }
        } catch (\Exception $e) {
            if ($e->getMessage() == "Connection refused") {
                if ($reties == $retryLimit) {
                    echo "尝试次数达到";
                } else {
                    sleep(1);
                    ++$reties;
                    var_dump("尝试次数", $reties);
                    goto  RETRY;
                }
            }

        }
    }
});

$pool->on("WorkerStop", function ($pool, $workerId) {
    echo "Worker#{$workerId} is stopped\n";
});

$pool->start();